from datetime import datetime
from app import db
from app.models.tag import Tag
from app.models.question_tag import QuestionTag

class Question(db.Model):
    __tablename__ = 'questions'
    
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255), nullable=False, index=True)
    content = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.utcnow, index=True)
    update_time = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
    view_count = db.Column(db.Integer, default=0)
    
    # 关系
    answers = db.relationship('Answer', backref='question', lazy='dynamic', cascade='all, delete-orphan')
    tags = db.relationship('Tag', secondary='question_tags', 
        backref=db.backref('questions', lazy='dynamic'), 
        lazy='dynamic')
    
    # 创建联合索引
    __table_args__ = (
        db.Index('idx_title_content', 'title', 'content'),
    )
    
    def __repr__(self):
        return f'<Question {self.title}>'
    
    def add_tag(self, tag):
        if not self.has_tag(tag):
            self.tags.append(tag)
    
    def remove_tag(self, tag):
        if self.has_tag(tag):
            self.tags.remove(tag)
    
    def has_tag(self, tag):
        return self.tags.filter_by(id=tag.id).first() is not None
    
    def to_dict(self):
        return {
            'id': self.id,
            'title': self.title,
            'content': self.content,
            'create_time': self.create_time,
            'update_time': self.update_time,
            'user_id': self.user_id,
            'view_count': self.view_count,
            'answers_count': self.answers.count(),
            'tags': [tag.name for tag in self.tags]
        } 